import React from "react";
import {Icon, message, Spin, Popover} from 'antd';
import FeeReportService from "containers/data-center/report/travel-report/fee-report/fee-report.service";
import 'styles/data-center/report/travel-report/fee-report/fee-report.scss';
import Charts from 'components/echarts';
import VscrollCharts from 'components/template/vscroll-echarts/vscroll-echarts';
import SearchArea from 'components/search-area';
import {messages} from "share/common";
import menuRoute from 'routes/menuRoute';
import noDataImg from 'images/no-data.png';
import configureStore from 'stores';
import FRDEService from 'containers/data-center/report/travel-report/fee-report/fee-report-data-engine.service';
import FeeReportOverview from 'containers/data-center/report/travel-report/fee-report/fee-report-overview';
import UserDetailExpense from 'containers/data-center/report/travel-report/fee-report/components/user-detail-expense'
import CostCenterSearchForm from 'containers/data-center/report/travel-report/fee-report/components/cost-center-search-form/cost-center-search-form'
import CostCenterChart from 'containers/data-center/report/travel-report/fee-report/components/cost-center-chart/cost-center-chart'

class FeeReport extends React.Component {
  constructor(props) {
    super(props);
    this.CTS = [];
    /*
    * CTS 存入被点击的类型数据
    * eg
    * let a = {
    *   type: "departmentExpenseReport",
    *   options: {}
    * }
    * */
    this.state = {
      echartsHeight: 400,
      showSearchArea: true,
      key: 0,
      loading: false,
      isSearching: false,
      searchParams: {},//搜索参数
      searchForm: [],//搜索组件
      allData: {
        departmentExpenseReport: {},
        expenseTendencyReport: {},
        expenseTypeReport: {},
        statusAmountReport: {},
        userExpense: {},
        costCenterReport: {}
      },
    }
  }

  componentDidMount() {
    this.InitSearchComponents();
  }

  //初始化搜索组件
  InitSearchComponents = () => {
    FeeReportService.InitSearchComponents()
      .then((res) => {
        //设置搜索组件
        return FeeReportService.getFeeReportSearchForm()
          .then(searchForm => {
            this.setState({
              searchForm
            }, () => {
              //自动触发搜索账套改变时间，设置依赖项的初始值
              let val = FeeReportService.getDefaultValueById("filterSetOfBooksId", searchForm);
              this.eventSearchAreaHandle("books", val, () => {
                this.getAnalysisReport("default")
              })
            })
          })
      })
      .catch(() => {
        this.setState({
          isSearching: false
        })
      })
  }


  /*
  * 顶部数据+其他1-4个报表
  * @params searchParams 查询参数
  * @params triggerType 点击图表的类型
  * */
  getAnalysisReportAction = (searchParams, triggerType, isClickSearch) => {
    let allType = [
      'expenseTendencyReport',
      'expenseTypeReport',
      'departmentExpenseReport',
      'statusAmountReport',
      'userExpense',
      'costCenterReport'
    ];
    let getDataType = [];
    let key = this.state.key;
    getDataType = allType.filter(function (item) {
      return item !== triggerType
    });
    this.childLoadOverview.getReportDetailTotal(searchParams);
    this.childUserDetailExpense.refreshComponentLoading();
    FeeReportService.getAllDataBySearchParams(searchParams, getDataType, isClickSearch)
      .then(res => {
        let allData = FeeReportService.getCanRenderAllDateByApiRes(res, this.CTS);
        if (triggerType) {
          /*
           * 数据不要setState
           * 会导致整个页面组件刷新
           * */
          getDataType.map((type) => {
            this.resetChartOptionByName(type, allData[type][type + "Options"], allData)
          });
          this.childUserDetailExpense.refreshComponent(searchParams);
          // this.setState({
          //   isSearching: false
          // })
        } else {
          allData = FeeReportService.resetStyle(allData);
          key++;
          this.CTS = [];
          this.setState({
            key,
            allData,
            isSearching: false
          }, () => {
            this.childUserDetailExpense.refreshComponent(searchParams)
          })
        }
      })
      .catch(() => {
        this.setState({
          isSearching: false
        })
      })
  };
  getAnalysisReport = (isDefault, isClickSearch) => {
    let {searchParams} = this.state;
    searchParams.reportId = this.props.params.id;
    if (isDefault) {
      let companyFromFeeReport = configureStore.store.getState().login.company;
      searchParams.filterShowYOY = true;
      searchParams.filterIncludeSubDepts = true;
      searchParams.filterSetOfBooksId = companyFromFeeReport.setOfBooksId;
      searchParams.filterYear = (new Date()).getFullYear();
    }
    if ((searchParams.filterYear === "" || !searchParams.filterYear) && isDefault !== "clear") {
      message.warn(messages('data-center.key89')/*请选择年份*/);
      this.setState({
        isSearching: false
      });
      return;
    }
    //趋势报表单独获取
    this.getAnalysisReportAction(searchParams, undefined, isClickSearch);
  }
  //当搜索自动发送改变
  eventSearchAreaHandle = (e, item, callback) => {
    let setOfBooksId = item && item.length ? item[0].setOfBooksId : "";
    if (e === "books" && FeeReportService.checkSetOfBooksIsChange(setOfBooksId)) {
      typeof callback !== "function" && message.warn(messages('data-center.key69')/*您切换了账套，已清空公司、报销单类型、费用类型的筛选*/);
      this.formRef.setValues({
        filterExpenseTypeIds: undefined,
        filterFormOids: undefined,
        filterCompanyOids: undefined,
        filterStatus: undefined,
        filterApplicantOids: undefined
      });
      FeeReportService.resetSearchComponentsBySetOfBooksId(setOfBooksId)
        .then(res => {
          const {searchForm} = this.state;
          this.setState({
            searchForm
          }, () => {
            typeof callback === "function" && callback()
          })
        })
    }
  }
  //清空搜索
  clearSearchHandle = () => {
    this.setState({
      searchParams: {},
      isSearching: true
    }, () => {
      this.InitSearchComponents();
    })
  }
  //点击搜搜索
  handleSearch = (values) => {
    const {searchParams} = this.state;
    let params = Object.assign(searchParams, values);
    //账套单独处理
    params.filterSetOfBooksId = params.filterSetOfBooksId && params.filterSetOfBooksId.length > 0 ? params.filterSetOfBooksId[0] : "";
    this.setState({
      searchParams: params,
      isSearching: true
    }, () => {
      this.getAnalysisReport(false, true);
    })
  };
  /*
  * 重绘图表
  * 点击哪一个图表，哪一个图表就重绘
  * */
  resetChartOptionByName = (type, option, resAlldata) => {
    let allData = this.state.allData;
    allData[type] = resAlldata[type];
    switch (type) {
      case 'expenseTendencyReport': {
        this.childExpenseTendencyReport.resetChartOption(option);
        break;
      }
      case 'expenseTypeReport': {
        this.childExpenseTypeReport.resetChartOption(option);
        break;
      }
      case 'departmentExpenseReport': {
        this.childDepartmentExpenseReport.resetChartOption(option);
        break;
      }
      case 'statusAmountReport': {
        this.childStatusAmountReport.resetChartOption(option);
        break;
      }
      case 'userExpense': {
        this.childUserExpense.resetChartOption(option);
        break;
      }
      case 'costCenterReport': {
        this.childCostCenterReport && this.childCostCenterReport.resetChartOption(option);
        break;
      }
    }
  }
  mergeClickEventLogic = (type, params, chartIndex) => {
    let criteria = null;
    let {allData, searchParams} = this.state;
    let option = allData[type][type + "Options"];
    if (type === "expenseTendencyReport") {
      criteria = parseInt(params.data.month);
    } else {
      criteria = params.data.criteria;
    }
    if (params.color === "#00386b") {
      if (type === "expenseTendencyReport") {
        option.series[0].itemStyle = null;
        option.series[1].itemStyle = null;
        searchParams.filterYearMonths = undefined;
      }
      if (type === "expenseTypeReport") {
        option.series[0].itemStyle = null;
        searchParams.filterExpenseTypeIds = undefined;
      }
      if (type === "departmentExpenseReport") {
        option.series[0].itemStyle = null;
        searchParams.filterDepartmentCodes = undefined;
      }
      if (type === "statusAmountReport") {
        option.series[0].color = null;
        searchParams.filterStatus = undefined;
      }
      if (type === "userExpense") {
        option.series[0].itemStyle = null;
        searchParams.filterApplicantOids = undefined;
      }
      if (type === "costCenterReport") {
        FRDEService.setCostCenterItemStyleNull(option);
        searchParams.filterCostCenterItemOids = undefined;
      }
      /*
      * this.CTS 是 点击过的 图形报表的队列
      * 再次点击，需要从队列中去掉
      * */
      this.CTS = FeeReportService.deleteCTS(this.CTS, type)
    } else {
      if (type === "expenseTendencyReport") {
        option.series[0].itemStyle = FRDEService.getActiveItemStyle(params.dataIndex, option.series[0].data.length);
        option.series[1].itemStyle = FRDEService.getActiveItemStyle(params.dataIndex, option.series[0].data.length);
        searchParams.filterYearMonths = [criteria];
      }
      if (type === "expenseTypeReport") {
        option.series[0].itemStyle = FRDEService.getActiveItemStyleByName(params, option);
        searchParams.filterExpenseTypeIds = [criteria]
      }
      if (type === "departmentExpenseReport") {
        option.series[0].itemStyle = FRDEService.getActiveItemStyle(params.dataIndex, option.series[0].data.length);
        // 处理费用类型图表颜色
        searchParams.filterDepartmentCodes = [criteria]
      }
      if (type === "statusAmountReport") {
        option.series[0].color = FRDEService.getBarOptionsColors(params.dataIndex, option.series[0].data.length);
        searchParams.filterStatus = [criteria]
      }
      if (type === "userExpense") {
        option.series[0].itemStyle = FRDEService.getActiveItemStyle(params.dataIndex, option.series[0].data.length);
        searchParams.filterApplicantOids = [criteria]
      }
      if (type === "costCenterReport") {
        FRDEService.setCostCenterItemStyleActive(option, params, chartIndex);
        searchParams.filterCostCenterItemOids = [criteria]
      }
      this.CTS = FeeReportService.addCTS(this.CTS, type, option, params)
    }
    //其他几个非当前点击报表
    this.getAnalysisReportAction(searchParams, type);
    //当前点击的报表
    this.resetChartOptionByName(type, option, allData);
  }
  //点击费用趋势报表
  clickExpenseTendencyReport = (params) => {
    this.mergeClickEventLogic("expenseTendencyReport", params)
  };
  //点击费用类型报表
  clickExpenseTypeReport = (params) => {
    this.mergeClickEventLogic("expenseTypeReport", params)
  };
  //部门费用
  clickDepartmentExpenseReport = (params) => {
    this.mergeClickEventLogic("departmentExpenseReport", params)
  };
  //点击 报销单状态
  clickStatusAmountReport = (params) => {
    this.mergeClickEventLogic("statusAmountReport", params)
  };
  //点击 人员费用
  clickUserExpense = (params) => {
    this.mergeClickEventLogic("userExpense", params)
  };
  //点击成本中心
  clickCostCenterReport = (params, chartIndex) => {
    this.mergeClickEventLogic("costCenterReport", params, chartIndex)
  }
  //挂载子组件到当前容器：趋势报表
  onMountExpenseTendencyReport = (expenseTendencyReport) => {
    this.childExpenseTendencyReport = expenseTendencyReport;
  };
  onMountDepartmentExpenseReport = (departmentExpenseReport) => {
    this.childDepartmentExpenseReport = departmentExpenseReport;
  };
  onMountExpenseTypeReport = (expenseTypeReport) => {
    this.childExpenseTypeReport = expenseTypeReport;
  };
  onMountStatusAmountReport = (statusAmountReport) => {
    this.childStatusAmountReport = statusAmountReport;
  };
  onMountUserExpense = (userExpense) => {
    this.childUserExpense = userExpense;
  };
  onMountUserDetailExpense = (userDetailExpense) => {
    this.childUserDetailExpense = userDetailExpense;
  }
  onMountLoadOverview = (feeReportOverview) => {
    this.childLoadOverview = feeReportOverview;
  }
  onMountCostCenterReport = (costCenterReport) => {
    this.childCostCenterReport = costCenterReport;
  }
  renderChartTitle=(type, od)=>{
    let _type = type+"Options";
    let title = od[_type] ? od[_type].title._text : "";
    return title

  }
  renderChart = (type, od) => {
    let echartsHeight = this.state.echartsHeight;
    //0.33 宽度；-12 padding； -10 滚动条宽度； -2 浮动
    let width = (document.getElementsByClassName('helios-content')[0].offsetWidth - 40)* 0.33 - 12 - 10 - 2;
    if (od[type] && od[type].length > 0) {
      switch (type) {
        case "expenseTendencyReport": {
          return (<Charts options={od.expenseTendencyReportOptions}
                          height={echartsHeight}
                          width="100%"
                          clickEcharts={this.clickExpenseTendencyReport}
                          onRef={this.onMountExpenseTendencyReport}
                          className="echarts-item"/>);

          break;
        }
        case "expenseTypeReport": {
          return (<VscrollCharts options={od.expenseTypeReportOptions}
                           height={echartsHeight}
                           width={width}
                           wrapClassName={'echarts-item-expenseTypeReport'}
                           clickEcharts={this.clickExpenseTypeReport}
                           onRef={this.onMountExpenseTypeReport}
                           className="echarts-item"/>);
          break;
        }
        case "departmentExpenseReport": {
          //高度一定，渲染的时候根据滚动时间进行渲染
          return (<VscrollCharts options={od.departmentExpenseReportOptions}
                           height={echartsHeight}
                           width={width}
                           wrapClassName={'echarts-item-departmentExpenseReport'}
                           clickEcharts={this.clickDepartmentExpenseReport}
                           onRef={this.onMountDepartmentExpenseReport}
                           className="echarts-item"/>);
          break;
        }
        case "statusAmountReport": {
          return (<Charts options={od.statusAmountReportOptions}
                          height={echartsHeight}
                          clickEcharts={this.clickStatusAmountReport}
                          onRef={this.onMountStatusAmountReport}
                          className="echarts-item"/>);
          break;
        }
        case "userExpense": {
          return (<VscrollCharts options={od.userExpenseOptions}
                           height={echartsHeight}
                           width={width}
                           wrapClassName={'echarts-item-userExpense'}
                           clickEcharts={this.clickUserExpense}
                           onRef={this.onMountUserExpense}
                           className="echarts-item"/>);
          break;
        }
        case "costCenterReport": {
          return <CostCenterChart
            echartsHeight={echartsHeight}
            echartsWidth={width}
            clickEcharts={this.clickCostCenterReport}
            options={od.costCenterReportOptions}
            onRef={this.onMountCostCenterReport}
          />;
        }
      }
    } else {
      return <div className="no-data-wrap">
        <img src={noDataImg}/>
        <p className="no-data-desc">{messages('data-center.key90')/*暂无数据*/}</p>
      </div>
    }
  }
  //返回到列表
  handleBack = () => {
    let path = menuRoute.getRouteItem('report', 'key').url;
    this.context.router.push(path);
  };

  showSearchAreaHandler = () => {
    this.setState({
      showSearchArea: true
    })
  }
  hideSearchAreaHandler = () => {
    this.setState({
      showSearchArea: false
    })
  }
  changeCostCenter = (value) => {
    const {searchParams} = this.state;
    searchParams.searchCostCenterCommands = value;
    this.setState({searchParams})
  };

  render() {
    const {
      loading,
      key,
      allData,
      showSearchArea,
      searchParams,
      isSearching
    } = this.state;
    let className = showSearchArea ? 'show-sa' : "hidden-sa";
    let extraFields = [
      <div>
        <div className='extra-sa-title'>
          {messages('financial-management.key145'/*成本中心*/)}
        </div>
        <CostCenterSearchForm title={messages('financial-management.key145'/*成本中心*/)}
                              value={searchParams.searchCostCenterCommands}
                              onChange={this.changeCostCenter}/>
      </div>
    ];

    return (
      <div className="fee-report-setting-wrap">
        <div className='s-wrap'>
          <div className='search-area-btn-wrap'>
            {!showSearchArea && <div className="show-search-area-btn-top" onClick={this.showSearchAreaHandler}>
              <Popover content={messages('data-center.key114')/*展开收起搜索区*/}><Icon
                type="caret-down"/></Popover>
            </div>}
          </div>
          <div className={className}>
            <SearchArea
              extraFields={extraFields}
              extraFieldsIndex={2}
              wrappedComponentRef={(inst) => this.formRef = inst}
              eventHandle={this.eventSearchAreaHandle}
              searchForm={this.state.searchForm}
              clearHandle={this.clearSearchHandle}
              submitHandle={this.handleSearch}
              loading={isSearching}/>
          </div>
          <div className='search-area-btn-wrap'>
            {showSearchArea && <div className="show-search-area-btn" onClick={this.hideSearchAreaHandler}>
              <Popover content={messages('data-center.key115')/*收起搜索区*/}><Icon
                type="caret-up"/></Popover>
            </div>}
          </div>
        </div>
        <div className='fee-report-inner-wrap'>
          <FeeReportOverview onRef={this.onMountLoadOverview}/>
          <div className='echarts-wrap' key={key}>
            {/*key 需要加上，解决 echart 的bug，渲染两层图，导致点击一下，有多次事件触发*/}
            <div className="tendency-report-title-wrap">
              <div className="echarts-title">{messages('data-center.key68')/*费用总体趋势报表*/}</div>
              <div className="tendency-report-wrap">
                <Spin spinning={loading}>
                  {this.renderChart('expenseTendencyReport', allData.expenseTendencyReport)}
                </Spin>
              </div>
            </div>

            <div>
              <div className="echarts-item-title-wrap">
                <div className="echarts-title">
                  {this.renderChartTitle('expenseTypeReport', allData.expenseTypeReport)}
                </div>
                <div className="echarts-item-wrap">
                  <Spin spinning={loading}>
                    {this.renderChart('expenseTypeReport', allData.expenseTypeReport)}
                  </Spin>
                </div>
              </div>

              <div className="echarts-item-title-wrap">
                <div className="echarts-title">
                  {this.renderChartTitle('departmentExpenseReport', allData.departmentExpenseReport)}
                </div>
                <div className="echarts-item-wrap">
                  <Spin spinning={loading}>
                    {this.renderChart('departmentExpenseReport', allData.departmentExpenseReport)}
                  </Spin>
                </div>
              </div>

              <div className="echarts-item-title-wrap">
                <div className="echarts-title">{messages('data-center.key128')/*报销单状态占比*/}</div>
                <div className="echarts-item-wrap over-hide">
                  <Spin spinning={loading}>
                    {this.renderChart('statusAmountReport', allData.statusAmountReport)}
                  </Spin>
                </div>
              </div>

              <div className="clear"/>
              {/*echarts-item-half-wrap*/}
              <div className="echarts-item-title-wrap">
                <div className="echarts-title">
                  {this.renderChartTitle('userExpense', allData.userExpense)}
                </div>
                <div className="echarts-item-wrap">
                  <Spin spinning={loading}>
                    {this.renderChart('userExpense', allData.userExpense)}
                  </Spin>
                </div>
              </div>

              <div className="echarts-item-title-wrap echarts-item-user-detail">
                <UserDetailExpense
                  onRef={this.onMountUserDetailExpense}/>
              </div>
              <div className="clear"/>

              {/*渲染成本中心*/}
              <div className='cost-center-chart-warp'>
                {this.renderChart('costCenterReport', allData.costCenterReport)}
              </div>
              <div className="clear"/>
            </div>
          </div>
        </div>
        <div>
          <a className='back-a' onClick={this.handleBack}>
            <Icon className='back-a-icon' type="rollback" />
            {messages('common.back')}
          </a>
        </div>
      </div>
    )
  }
}

FeeReport.contextTypes = {
  router: React.PropTypes.object
};
export default FeeReport;
